package com.lw.leetcode.arr.b;

import com.lw.leetcode.linked.ListNode;

/**
 * Created with IntelliJ IDEA.
 * 6111. 螺旋矩阵 IV
 *
 * @author liw
 * @version 1.0
 * @date 2022/7/3 22:29
 */
public class SpiralMatrix {
    public int[][] spiralMatrix(int m, int n, ListNode head) {
        int[][] arr = new int[m][n];
        if (m == 1 && n == 1) {
            arr[0][0] = head == null ? -1 : head.val;
            return arr;
        }
        int ast = 0;
        int bst = 0;
        int aend = m - 1;
        int bend = n - 1;
        while (ast <= aend && bst <= bend) {
            for (int i = bst; i < bend; i++) {
                if (head != null) {
                    arr[ast][i] = head.val;
                    head = head.next;
                } else {
                    arr[ast][i] = -1;
                }
            }
            for (int i = ast; i < aend; i++) {
                if (head != null) {
                    arr[i][bend] = head.val;
                    head = head.next;
                } else {
                    arr[i][bend] = -1;
                }
            }
            if (ast != aend) {
                for (int i = bend; i > bst; i--) {
                    if (head != null) {
                        arr[aend][i] = head.val;
                        head = head.next;
                    } else {
                        arr[aend][i] = -1;
                    }
                }
            } else {
                if (head != null) {
                    arr[aend][bend] = head.val;
                    head = head.next;
                } else {
                    arr[aend][bend] = -1;
                }
            }
            if (bst != bend) {
                for (int i = aend; i > ast; i--) {
                    if (head != null) {
                        arr[i][bst] = head.val;
                        head = head.next;
                    } else {
                        arr[i][bst] = -1;
                    }
                }
            } else {
                if (head != null) {
                    arr[aend][bend] = head.val;
                    head = head.next;
                } else {
                    arr[aend][bend] = -1;
                }
            }
            ast++;
            aend--;
            bst++;
            bend--;
        }
        return arr;
    }

}
